package com.zoffy.wmsbackend.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zoffy.wmsbackend.model.dto.stock.SafeStockVo;
import com.zoffy.wmsbackend.model.dto.stock.StockQueryDTO;
import com.zoffy.wmsbackend.model.entity.Stock;
import com.zoffy.wmsbackend.model.excel.bean.StockPurchaseVo;
import com.zoffy.wmsbackend.model.vo.stock.StockVO;
import com.zoffy.wmsbackend.service.StockService;
import com.zoffy.wmsbackend.common.BaseResponse;
import com.zoffy.wmsbackend.common.ResultUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@PreAuthorize("hasAuthority('admin')")
@RequestMapping("/stock")
public class StockController {
    @Resource
    private StockService stockService;

    @PostMapping("/list")
    public BaseResponse<IPage<StockVO>> queryStock(@RequestBody StockQueryDTO queryDTO) {
        IPage<StockVO> stockList = stockService.selectStockPage(queryDTO);
        return ResultUtils.success(stockList);
    }
    @GetMapping("/exportBelowSafeLevel")
    public void exportStockBelowSafeLevel(HttpServletResponse response) throws IOException {
        List<StockPurchaseVo> stockList = stockService.selectStockBelowSafeLevel();

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("库存不足货品信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        EasyExcel.write(response.getOutputStream(), StockPurchaseVo.class).sheet("库存不足货品信息").doWrite(stockList);
    }
    @PostMapping("/updateSafeStock")
    public void updateSafeStock(@RequestBody SafeStockVo safeStockVo) {
        Long warehouseId = safeStockVo.getWarehouseId();
        Long goodsId = safeStockVo.getGoodsId();
        Integer safeStock = safeStockVo.getSafeStock();
        if(warehouseId == null || goodsId == null || safeStock == null) {
            return ;
        }

        QueryWrapper<Stock> wrapper = new QueryWrapper<>();
        wrapper.eq("warehouse_id", warehouseId);
        wrapper.eq("goods_id", goodsId);
        Stock stock = stockService.getOne(wrapper);
        if(stock == null) {
            stock = new Stock();
            stock.setWarehouseId(warehouseId);
            stock.setGoodsId(goodsId);
            stock.setQuantity(0);
        }
        stock.setSafeStock(safeStock);
        stockService.saveOrUpdate(stock);

    }
}
